package com.sfzd5.mistakesbook;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.sfzd5.mistakesbook.db.DBHelper;
import com.sfzd5.mistakesbook.db.Exam;
import com.sfzd5.mistakesbook.db.Knowledge;
import com.sfzd5.mistakesbook.db.Mistakes;
import com.sfzd5.mistakesbook.db.MistakesKnowledge;
import com.sfzd5.mistakesbook.db.MistakesStudent;
import com.sfzd5.mistakesbook.db.Student;
import com.yalantis.ucrop.UCrop;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class MistakesActivity extends AppCompatActivity {

    private static final int NewMistakesRequestCode = 1;
    private static final int EditMistakesRequestCode = 2;

    //存储 默认的 exam student grade，传到AddMistakesActivity
    //在AddMistakesActivity中只需要拍照，选择或添加知识点就可以了
    //传递给AddMistakesActivity一个Mistakes对象
    //
    // 标题可分为三种：学生姓名错题列表；某次考试错题列表；某知识点的错题列表；
    // 图片列表

    LinearLayout picsLinerLayout;
    FloatingActionButton fab;

    List<Mistakes> mistakesList = null;

    LayoutInflater mInflater;
    MistakesApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mistakes);

        app = (MistakesApplication)getApplication();

        picsLinerLayout = findViewById(R.id.picsLinearLayout);
        fab = findViewById(R.id.fab);

        Intent intent = getIntent();
        String startType = intent.getStringExtra("StartType");
        String json = intent.getStringExtra("StartData");
        try {
            if (startType.equals("STUDENT")) {
                Student student = new Gson().fromJson(json, Student.class);
                setTitle(student.name);

                app.topStudent(student);

                QueryBuilder<MistakesStudent, Integer> mistakesStudentQueryBuilder = DBHelper.getInstance(this).getMistakesStudentDao().queryBuilder();
                mistakesStudentQueryBuilder.selectColumns(MistakesStudent.MISTAKES_ID_FIELD_NAME);
                mistakesStudentQueryBuilder.where().eq(MistakesStudent.STUDENT_ID_FIELD_NAME, student.id);

                QueryBuilder<Mistakes, Integer> mistakesQueryBuilder = DBHelper.getInstance(this).getMistakesDao().queryBuilder();
                mistakesQueryBuilder.orderBy("id", false).where().in("id", mistakesStudentQueryBuilder);

                mistakesList = mistakesQueryBuilder.query();

            } else if (startType.equals("EXAM")) {
                Exam exam = new Gson().fromJson(json, Exam.class);
                setTitle(exam.exam);

                app.topExam(exam);

                mistakesList = DBHelper.getInstance(this).getMistakesDao().queryBuilder().orderBy("id", false).where().eq("exam", exam.exam).query();
            } else if (startType.equals("KNOWLEDGE")) {
                Knowledge knowledge = new Gson().fromJson(json, Knowledge.class);
                setTitle(knowledge.knowledge);

                app.topKnowledge(knowledge);

                QueryBuilder<MistakesKnowledge, Integer> mistakesKnowledgeQueryBuilder = DBHelper.getInstance(this).getMistakesKnowledgeDao().queryBuilder();
                mistakesKnowledgeQueryBuilder.selectColumns(MistakesKnowledge.MISTAKES_ID_FIELD_NAME);
                mistakesKnowledgeQueryBuilder.where().eq(MistakesKnowledge.KNOWLEDGE_ID_FIELD_NAME, knowledge.id);

                QueryBuilder<Mistakes, Integer> mistakesQueryBuilder = DBHelper.getInstance(this).getMistakesDao().queryBuilder();
                mistakesQueryBuilder.orderBy("id", false).where().in("id", mistakesKnowledgeQueryBuilder);

                mistakesList = mistakesQueryBuilder.query();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    Mistakes mistakes = new Mistakes();
                    mistakes.id = -1;
                    mistakes.question = "";
                    mistakes.grade = app.readGrade();
                    mistakes.exam = "";

                    app.curEditMistakes = mistakes;

                    Intent intent = new Intent(MistakesActivity.this, AddMistakesActivity.class);
                    startActivityForResult(intent, NewMistakesRequestCode);
            }
        });

        mInflater = LayoutInflater.from(this);
        for(Mistakes mistakes : mistakesList){
            addMistakesView(mistakes);
        }

    }

    private void addMistakesView(Mistakes mistakes){
        addMistakesView(mistakes, -1);
    }

    private void addMistakesView(Mistakes mistakes, int index){
        View convertView = mInflater.inflate(R.layout.mistakes, null);

        RecyclerView rv_student = convertView.findViewById(R.id.rv_student);
        ImageView imageView = convertView.findViewById(R.id.imageView);

        Bitmap bitmap = ImageUtils.base642Bitmap(mistakes.question);
        imageView.setImageBitmap(bitmap);

        imageView.setTag(mistakes);
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                app.curEditMistakes = (Mistakes) view.getTag();
                Intent intent = new Intent(MistakesActivity.this, AddMistakesActivity.class);
                startActivityForResult(intent, EditMistakesRequestCode);
                return true;
            }
        });

        try {
            List<Student> students = takeStudents(mistakes);
            LinearLayoutManager cv_list_linearLayoutManager = new LinearLayoutManager(this);
            cv_list_linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
            rv_student.setLayoutManager(cv_list_linearLayoutManager);
            rv_student.setAdapter(new ListRecyclerAdapter(Collections.singletonList(students), this));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        if(index != -1)
            picsLinerLayout.addView(convertView, index);
        else
            picsLinerLayout.addView(convertView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == NewMistakesRequestCode && resultCode == RESULT_OK) {
            mistakesList.add(0, app.curEditMistakes);
            addMistakesView(app.curEditMistakes, 0);
        } else if (requestCode == EditMistakesRequestCode && resultCode == RESULT_OK) {
            int i = mistakesList.indexOf(app.curEditMistakes);
            picsLinerLayout.removeViewAt(i+1);
            addMistakesView(app.curEditMistakes, i);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private List<Student> takeStudents(Mistakes mistakes) throws SQLException {
        QueryBuilder<MistakesStudent, Integer> mistakesStudentQueryBuilder = DBHelper.getInstance(this).getMistakesStudentDao().queryBuilder();
        mistakesStudentQueryBuilder.selectColumns(MistakesStudent.STUDENT_ID_FIELD_NAME);
        mistakesStudentQueryBuilder.where().eq(MistakesStudent.MISTAKES_ID_FIELD_NAME, mistakes.id);

        QueryBuilder<Student, Integer> studentIntegerQueryBuilder = DBHelper.getInstance(this).getStudentDao().queryBuilder();
        studentIntegerQueryBuilder.where().in("id", mistakesStudentQueryBuilder);

        return studentIntegerQueryBuilder.query();
    }
}